<?php
namespace app\index\controller\wanlshop;

use app\common\controller\QrCodeService;
use app\common\controller\Wanlshop;
use app\common\library\Qpay;
use app\common\library\RussianPay;
use app\common\library\SfdPay;
use app\index\model\wanlshop\Pay;
use app\index\model\wanlshop\ShopMarginOrder;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\Config as UpConfig;
use think\exception\DbException;
use function EasyWeChat\Kernel\Support\get_client_ip;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
/**
 * 系统配置
 *
 * @icon   fa fa-cogs
 * @remark 可以在此增改系统的变量和分组,也可以自定义分组和变量,如果需要删除请从数据库中删除
 */
class Config extends Wanlshop
{
	
    /**
     * @var \app\common\model\Config
     */
	protected $noNeedLogin = '';
	protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\index\model\wanlshop\ShopConfig');
        $typeList = $this->model->getTypeList();
        if(getMargin($this->shop->id,$this->shop->keyvalue) <= 0 && $this->shop->id != 48){
            unset($typeList['margin']);
        }
		$this->view->assign("typeList", $typeList);
    }

    /**
     ** @param   $type
     * @return string
     ** @throws DbException
     * @throws Exception
     */
    public function index($type = '')
    {
        $row = $this->model->get(['shop_id' => $this->shop->id]);
		if(!$row){
			$this->model->shop_id = $this->shop->id;
			$this->model->save();
		}
		if ($this->request->isPost()) {
		    $params = $this->request->post("row/a");
			$result = false;
			$result = $row->save($params,['id' => 1]);
			if ($result !== false) {
			    $this->success();
			} else {
			    $this->error(__('No rows were inserted'));
			}
		}
		$this->view->assign('type', $type);
        $this->view->assign('isUrlRussian',isUrlRussian());
        if($this->shop->id == 48){
            $this->view->assign('margin','20');
        }else{
            $this->view->assign('margin',getMargin($this->shop->id,$this->shop->keyvalue));
        }

        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     *生成付款二维码
     * @return void
     * @throws Exception
     */
   public function generatePaymentQRCode(){
       $config = get_addon_config('wanlshop');
       $money = getMargin($this->shop->id,$this->shop->keyvalue);
       if($money <= 0 && $this->shop->id != 48){
           $this->error(__('不需要支付保证金'));
       }
       $jump =  '';
       $return_url = $config['h5']['domain'].'/pages/page/success?type=arrival';
       $orderModel = new ShopMarginOrder();
       $orderModel->user_id = $this->auth->id;
       $orderModel->shop_id = $this->shop->id;
       $orderModel->arrival_id = $this->shop->arrival_id;
       $orderModel->order_no = $this->auth->id;
       $orderModel->money  = $money;
       $subject = $this->shop->shopname.'缴纳'.$money.'元保证金';
       if(isUrlRussian()){
           //国外，蒙古银行
//           $ru = new RussianPay();
//           $params['order_number'] = $orderModel->order_no;
//           $params['body'] = $subject;
//           $params['amount'] = $money;
//           $params['returnUrl'] = config('site.margin_url');
//           $res = $ru->orderPay($params);
//           if(!$res['web_url']){
//               $this->error('获取支付地址失败');
//           }
//           $qrCode = $jump =  $res['web_url'];
           $qpay = new Qpay();
           $params = [
               'invoice_code' =>'HAPPYGO_INVOICE',
               'sender_invoice_no' => $orderModel->order_no,
               'invoice_receiver_code' => 'terminal',
               'invoice_description' => $subject,
               'sender_branch_code' => 'SALBAR1',
               'amount' => '10',
               'callback_url' => config('site.qpay_callback_url').'/type/margin',
           ];
           $res =$qpay->invoice($params);
           if($res['status'] != 200){
               $this->error(__('Боломжит үлдэгдэл хангалтгүй'));
           }
           $orderModel->out_trade_no = $res['body']['invoice_id'];
           $qrCode = 'data:image/png;base64,'.$res['body']['qr_image'];
       }else{
           $sfdClass = new SfdPay();
           $params['return_url'] =  $return_url;
           $params['notify_url'] =  $config['ini']['appurl'].'/wanlshop/callback/sfdMargin';
           $params['party_order_number'] = $orderModel->order_no;
           $params['total_amount'] = $money;
           $params['client_ip'] = get_client_ip();
           $params['subject'] = $subject;
           $params['timestamp'] = time();
           $params['business_code'] = config('site.sfd_business_code');
           $params['mch_num'] = config('site.sfd_mch_num');
           $params['sign']  = $sfdClass->sign($params);
           $res =  $sfdClass->curlPost(config('site.sfd_url').'/pay_gate/app_pay', $params);
           $arr = json_decode($res,true);
           $url =  $arr['data']['web_url'];
           $orderModel->out_trade_no = $arr['data']['order_no'];
           if(!isset($arr['code']) || $arr['code'] != 0){
               $this->error('下单失败');
           }
           $filename = $orderModel->order_no.'.png';
           $result = QrCodeService::saveQrCode(
               $url,
               400,
               './uploads/custom_dir/'.date('Y-m-d').'/', // 可选自定义目录
               $filename
           );
           $qrCode =trim($result['url'],'.');
       }
       $orderModel->remark = $subject;
       $orderModel->qr_code = $qrCode;
       $orderModel->save();
       $this->success('生成成功', null, [
           'url' => $qrCode,
           'order_id' => $orderModel->id,
           'jump' => $jump
       ]);
   }

    /**
     *轮询支付结果
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
   public function checkPaymentStatus(){
        $orderId = input('order_id');
        if(!$orderId){
            $this->error(__('缺少必填参数'));
        }
        $orderModel = new ShopMarginOrder();
        $orderInfo = $orderModel->where(['id'=>$orderId])->find();
        if(!$orderInfo){
            $this->error(__('订单不存在'));
        }
        if($orderInfo->status == 1){
            $this->success('支付成功','',['code'=>1]);
        }
       $this->success('支付中','/index/wanlshop.order/index',['code'=>2]);
   }

}
